package com.yanshaohui.controller;

import com.yanshaohui.bean.Person;
import com.yanshaohui.configuations.reactiveRedis.PersonRedisTemplate;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Random;

/**
 * Created by TS-Ysh on 2018-05-14.
 */
@RestController
public class ReactMongoController {

    private final Logger logger = Logger.getLogger(getClass());

    /**
     * spring-boot-starter-data-mongodb-reactive提供的通用模板
     */
    @Autowired
    private ReactiveMongoTemplate reactiveMongoTemplate;

    @RequestMapping("/mongo/save/person/{id}/{name}")
    public Mono<Person> savePerson(@PathVariable("id") Long id, @PathVariable("name") String name){
        return reactiveMongoTemplate.insert(new Person(id,name,1,"宇宙",23));
    }

    /**
     * 错误的，无法自动生成long型的id
     * org.springframework.dao.InvalidDataAccessApiUsageException: Cannot autogenerate id of type java.lang.Long for entity of type com.yanshaohui.bean.Person!
     * @return
     */
    @RequestMapping("/mongo/save/person")
    public Mono<Person> savePerson2(){
        Person p = new Person();
        p.setName("AAA");
        p.setAddress("地球" + new Random().nextInt(1000));
        return reactiveMongoTemplate.insert(p);
    }

    @RequestMapping("/mongo/get/person/{id}")
    public Mono<Person> getPerson(@PathVariable("id") Long id){
        return reactiveMongoTemplate.findById(id,Person.class);
    }

    @RequestMapping("/mongo/get/persons")
    public Flux<Person> getAll(){
        return reactiveMongoTemplate.query(Person.class).all();
    }
}
